package com.settlement.system.service.impl;

import com.settlement.system.common.util.common.AcsThreadPoolUtils;
import com.settlement.system.common.util.common.DateUtil;
import com.settlement.system.common.util.common.FasUtil;
import com.settlement.system.mapper.BaseMapper;
import com.settlement.system.mapper.TblCostWeightOrderMapper;
import com.settlement.system.mapper.TblCostWeightSummaryMapper;
import com.settlement.system.common.enums.CostAllocationWeightEnum;
import com.settlement.system.common.exception.ServiceException;
import com.settlement.system.model.entity.common.CommonPlugIn;
import com.settlement.system.model.entity.common.TblCostWeightRecord;
import com.settlement.system.model.entity.common.TblCostWeightSummary;

import com.settlement.system.service.ITblCostWeightRecordService;
import com.settlement.system.service.ITblCostWeightSummaryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;

/**
 * 【RR-费用分配权数】菜单 的 【发退货汇总】页签 服务实现类
 * @author xiaochuan
 * @since 2022-12-28
 */
@Slf4j
@Service
public class TblCostWeightSummaryServiceImpl extends BaseServiceImpl implements ITblCostWeightSummaryService {

    @Resource
    private TblCostWeightSummaryMapper tblCostWeightSummaryMapper;

    @Resource
    private TblCostWeightOrderMapper tblCostWeightOrderMapper;

    @Resource
    private ITblCostWeightRecordService tblCostWeightRecordService;

    private final ExecutorService executors = AcsThreadPoolUtils.getExecutorService();

    @Override
    public BaseMapper init() {
        return tblCostWeightSummaryMapper;
    }


    @Override
    public void saveSummaryCurrentMonth(Map<String,Object> params){
        tblCostWeightSummaryMapper.saveSummaryCurrentMonth(params);
    }

    @Override
    public void saveOrderNearlyThreeMonth(Map<String, Object> params){
        tblCostWeightSummaryMapper.saveOrderNearlyThreeMonth(params);
    }

    @Override
    public void saveSummaryNearlyThreeMonth(Map<String, Object> params){
        tblCostWeightSummaryMapper.saveSummaryNearlyThreeMonth(params);
    }



    @Override
    public String saveData(Map<String, Object> params) throws ServiceException {
        TblCostWeightRecord costWeightRecord = new TblCostWeightRecord();
        try {
            String channelNo = (String) params.get("channelNo");
            String actionType = (String) params.get("actionType");
            String weightType = (String) params.get("weightType");
            String accountingPeriod = (String) params.get("accountingPeriod");
            costWeightRecord.setChannelNo(channelNo);
            costWeightRecord.setWeightType(weightType);
            costWeightRecord.setAccountingPeriod(DateUtil.getDate(accountingPeriod,"yyyyMM"));
            costWeightRecord.setActionType(CostAllocationWeightEnum.ActionTypeEnum.T1.getNo());
            costWeightRecord.setStatus(CostAllocationWeightEnum.RecordStatusEnum.T1.getNo());
            costWeightRecord.setCreateTime(new Date());
            costWeightRecord.setCreateUser((String) params.get("createUser"));
            String oneSeq = tblCostWeightRecordService.getOneSeq();
            TblCostWeightRecord costWeightRecord1 = tblCostWeightRecordService.selectSingleByModel(costWeightRecord);
            if(costWeightRecord1!=null){
                return "已有操作进行中，请稍后再试。";
            }

            costWeightRecord.setId(oneSeq);
            tblCostWeightRecordService.insert(costWeightRecord);

            executors.submit(() -> {
                try{
                    if(CostAllocationWeightEnum.WeightTypeEnum.T1.getNo().equals(weightType)){
                        Date startDate = costWeightRecord.getAccountingPeriod();
                        Date endDate = DateUtil.getLastDayOfMonth(startDate);
                        params.put("startDate",DateUtil.format(startDate,"yyyy-MM-dd"));
                        params.put("endDate",DateUtil.format(endDate,"yyyy-MM-dd"));
                        params.put("accountingPeriod",DateUtil.format(startDate,"yyyyMM"));
                        FasUtil.formatInQueryCondition(params, "channelNo","companyNo");
                        saveSummaryCurrentMonth(params);
                    }else if(CostAllocationWeightEnum.WeightTypeEnum.T2.getNo().equals(weightType)){
                        Date startDate = costWeightRecord.getAccountingPeriod();
                        params.put("accountingPeriod",DateUtil.format(startDate,"yyyyMM"));

                        Date endDate = DateUtil.getLastDayOfMonth(startDate);
                        Date intStartDate = DateUtil.addMonth(startDate,-2);

                        params.put("intStartDate",DateUtil.format(intStartDate,"yyyy-MM-dd"));
                        params.put("startDate",DateUtil.format(startDate,"yyyy-MM-dd"));
                        params.put("endDate",DateUtil.format(endDate,"yyyy-MM-dd"));

                        FasUtil.formatInQueryCondition(params, "channelNo","companyNo");

                        saveOrderNearlyThreeMonth(params);
                        saveSummaryNearlyThreeMonth(params);
                    }

                    costWeightRecord.setStatus(CostAllocationWeightEnum.RecordStatusEnum.T2.getNo());
                    costWeightRecord.setUpdateTime(new Date());
                    tblCostWeightRecordService.update(costWeightRecord);
                    return null;
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                    costWeightRecord.setStatus(CostAllocationWeightEnum.RecordStatusEnum.T3.getNo());
                    costWeightRecord.setUpdateTime(new Date());
                    tblCostWeightRecordService.update(costWeightRecord);

                    throw new RuntimeException(e);
                }
            });
        }catch (Exception ex){
            log.error(ex.getMessage(),ex);
            throw new ServiceException(ex.getMessage(),ex);
        }
        return null;
    }

    @Override
    public String checkBeforeDelete(Map<String, Object> params) throws ServiceException {
        Map<String,Object> params2 = new HashMap<>(params);
        FasUtil.formatInQueryCondition(params2, "channelNo","companyNo","accountingPeriod","shopNo");
        Integer integer = tblCostWeightSummaryMapper.selectCountUsed(params2);
        if(integer>0){
            return "已生成分摊数据的明细 不允许删除";
        }
        return null;
    }

    @Override
    public List<CommonPlugIn> selectExistAccountPeriod() throws ServiceException {
        try{
            return tblCostWeightSummaryMapper.selectExistAccountPeriod();
        }catch (Exception ex){
            log.error(ex.getMessage(),ex);
            throw new ServiceException("selectExistAccountPeriod exception",ex);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer deleteByParams(Map<String, Object> params) throws ServiceException {
        try {

            String channelNo = (String) params.get("channelNo");
            String actionType = (String) params.get("actionType");
            String weightType = (String) params.get("weightType");
            String accountingPeriod = (String) params.get("accountingPeriod");
            TblCostWeightRecord costWeightRecord = new TblCostWeightRecord();
            costWeightRecord.setChannelNo(channelNo);
            costWeightRecord.setWeightType(weightType);
            costWeightRecord.setAccountingPeriod(DateUtil.getDate(accountingPeriod,"yyyyMM"));
            costWeightRecord.setActionType(CostAllocationWeightEnum.ActionTypeEnum.T2.getNo());
            costWeightRecord.setStatus(CostAllocationWeightEnum.RecordStatusEnum.T1.getNo());
            costWeightRecord.setCreateTime(new Date());
            costWeightRecord.setCreateUser((String) params.get("createUser"));
            String oneSeq = tblCostWeightRecordService.getOneSeq();
            costWeightRecord.setId(oneSeq);
            tblCostWeightRecordService.insert(costWeightRecord);

            Map<String,Object> params2 = new HashMap<>(params);

            FasUtil.formatInQueryCondition(params2, "channelNo","companyNo","accountingPeriod","shopNo");
            tblCostWeightSummaryMapper.deleteByParams(params2);
            tblCostWeightOrderMapper.deleteByParams(params2);

            costWeightRecord.setStatus(CostAllocationWeightEnum.RecordStatusEnum.T2.getNo());
            costWeightRecord.setUpdateTime(new Date());
            tblCostWeightRecordService.update(costWeightRecord);

            return null;
        }catch (Exception ex){
            log.error("deleteByParams error",ex);
            throw new ServiceException("deleteByParams error",ex);
        }
    }

    @Override
    public TblCostWeightSummary getFoot(Map<String, Object> params) throws ServiceException {
        try {
            return tblCostWeightSummaryMapper.getFoot(params);
        } catch (Exception ex) {
            log.error("获取合计异常", ex);
            throw new ServiceException("获取合计异常", ex);
        }
    }
}

